package com.apache.common.plugins;

import com.alibaba.fastjson.JSON;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.service.CacheManager;
import com.apache.cache.service.impl.LoadCacheFactory;
import com.apache.cache.service.impl.redis.RedisCoreFactory;
import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.tools.StrUtil;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname ZunlRoutesSynCachePluginImpl
 * @Description 路由存储缓存同步
 * @Date 2020/3/17 11:35
 * @Created by fpc
 */
public class ZunlRoutesSynCachePluginImpl implements CustomMethodPlugin {
    @Override
    public Object beforeInvoke(Map<String, Object> param) {
//        param.put()

        Map<String,Object> whereMap ;
        String serviceId = String.valueOf(param.get("sysZuulRoute.serviceId"));
        String path = String.valueOf(param.get("sysZuulRoute.path"));
        String modelTypes = String.valueOf(param.get("modelTypes"));
        whereMap = new HashMap<>();
        if(Validator.isNotNull(serviceId)){
            whereMap.put("sysZuulRoute.wo_serviceId",serviceId);
            whereMap.put("sysZuulRoute.wo_path",path);
        }else{
            whereMap.put("sysZuulRoute.w_path",path);
        }
        ResultEntity resultEntity = IusPluginUtil.getInstance().select("obj", "s_sysZuulRoute", whereMap);
        if(!Validator.isEmpty(resultEntity.getEntity())){
            if(modelTypes.startsWith("i_")){
                throw new BusinessException("【注册服务Id】或【过滤路径】已存在，请修改后重新提交注册。");
            }else{
                String w_infoId = String.valueOf(param.get("sysZuulRoute.w_infoId"));
                Map entity = (Map) resultEntity.getEntity();
                String infoId = String.valueOf(entity.get("infoId"));
                if(!infoId.equals(w_infoId)){
                    throw new BusinessException("【注册服务Id】或【过滤路径】已存在，请修改后重新提交注册。");
                }
                String routeType = String.valueOf(param.get("sysZuulRoute.routeType"));
                if("url".equals(routeType)){
                    param.put("sysZuulRoute.s_serviceId","is null");
                }else{
                    param.put("sysZuulRoute.s_url","is null");
                }
            }
        }

        param.put("afterMethodKey", "zunlRoutesSynCachePlugin");
        return null;
    }

    @Override
    public Object doInvoke(Map<String, Object> param) {
        return null;
    }

    @Override
    public Object afterInvoke(Map<String, Object> param) {
        CacheManager zuulRoutes = LoadCacheFactory.getInstance().getCacheManager("zuul.routes");

        String infoId = "";
        String modelTypes = String.valueOf(param.get("modelTypes"));
        Map<String,Object> whereMap = new HashMap<>();
        String enabled = String.valueOf(param.get("sysZuulRoute.enabled"));
        if("1".equals(enabled)){
            if(modelTypes.startsWith("i_")){
                Map<String,String> idMap = (Map<String,String>)param.get("resultIds");
                infoId = idMap.get("sysZuulRoute_infoId");
            }else {
                infoId = String.valueOf(param.get("sysZuulRoute.w_infoId"));
            }
            whereMap.put("sysZuulRoute.w_infoId",infoId);
            ResultEntity entity = IusPluginUtil.getInstance().select("obj", "s_sysZuulRoute", whereMap);
            if(!Validator.isEmpty(entity.getEntity())){
                zuulRoutes.createCacheObject(infoId,entity.getEntity());
            }
        } else {
            if(modelTypes.startsWith("u_")){
                infoId = String.valueOf(param.get("sysZuulRoute.w_infoId"));
                Map info = (Map)zuulRoutes.getCacheObjectByKey(infoId);
                if(info != null){
                    String cacheKey = String.valueOf(info.get("serviceId"));
                    if (StrUtil.isNull(cacheKey) && StrUtil.isNotNull(String.valueOf(info.get("url")))) {
                        cacheKey = String.valueOf(info.get("url"));
                    }
                    buildCacheInfo(cacheKey);
                }
                zuulRoutes.removeCacheObject(infoId);
            }
        }
/**
 * param = {HashMap@11299}  size = 28
 *  "sysZuulRoute.orgId" -> "4f5213b3dcb740c8abfd9bd5a86368c4"
 *  "logReqIp" -> "127.0.0.1"
 *  "sysZuulRoute.serviceName" -> "123"
 *  "sysZuulRoute.retryable" -> "1"
 *  "sysZuulRoute.enabled" -> "1"
 *  "modelTypes" -> "i_sysZuulRoute"
 *  "sqlKeyId" -> "zunlRoutesSynCachePlugin"
 *  "sysZuulRoute.delStatus" -> "F"
 *  "resultEntity" -> {HashMap@11388}  size = 1
 *  "resultIds" -> {HashMap@11388}  size = 1
 *  "sysZuulRoute.stripPrefix" -> "1"
 *  "formToken" -> "9ac75492-3fdf-4945-b047-83e3053c1914"
 *  "sysZuulRoute.path" -> "12331"
 *  "resultType" -> "processSql"
 *  "sysPass" -> "iussoft2018"
 *  "sysZuulRoute.deptId" -> "f08a18836276444d80130ecbcca2f7a4"
 *  "sysZuulRoute.versionNo" -> "null"
 *  "loginUser_userEname" -> "admin"
 *  "ParamType" -> "json"
 *  "afterMethodKey" -> "zunlRoutesSynCachePlugin"
 *  "logOperatorUser" -> "admin"
 *  "exe_rules" -> "null"
 *  "sysZuulRoute.serviceId" -> "123"
 *  "datasource" -> "plateform"
 *  "Client-IP" -> "127.0.0.1"
 *  "sysZuulRoute.createUser" -> "admin"
 *  "sysZuulRoute.createTime" -> "2020-03-17 14:55:18"
 *  "rulePrimaryKey" -> "sysZuulRoute"
 */


        return null;
    }

    private void buildCacheInfo(String key){
        Jedis jedis = null;
        try{
            jedis = RedisCoreFactory.getInstance().getJedis();
            jedis.select(10);
            jedis.hdel("zuul.routs", key);
        }catch (Exception e){
        }finally{
            if(null != jedis){
                jedis.close();
            }
        }
    }
}
